import {Injectable} from '@nestjs/common';
import {JwtService} from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import {UserService} from "../user/user.service";
import {LoginDto} from "./dto/login.dto";

@Injectable()
export class AuthService {

    constructor(
        private readonly userService: UserService,
        private readonly jwtService: JwtService,
    ) {
    }

    async validateUser(name: string, password: string) {

        const user = await this.userService.findByUsername(name);
        if (user && await bcrypt.compare(password, user.password)) {
            const {password, ...result} = user; // 去除密码
            return result;
        }
        return null;
    }

    async login(loginDto: LoginDto) {
        const {name, password} = loginDto;
        const user = await this.validateUser(name, password);

        if (!user) {
            throw new Error('用户名或密码错误');
        }

        const payload = {
            sub: user.id,
            username: name,
            timestamp: new Date().toISOString(),
        };

        return {
            access_token: this.jwtService.sign(payload),
        }
    }

    // 注册
    async register(registerDto: any) {
        const hashedPassword = await bcrypt.hash(registerDto.password, 10);
        return this.userService.create({
            ...registerDto,
            password: hashedPassword,
        });
    }

}
